package com.itheima.sms.config;

import com.itheima.sms.listener.MyListener;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import javax.annotation.Resource;

/**
 * 订阅发布模式的容器配置
 *
 * @author llhuang10
 * @date 2021/9/23 15:19
 */
@Configuration
@AutoConfigureAfter({MyListener.class})
public class SubscriberConfig {

    @Resource
    private MyListener myListener;

    /**
     * 创建消息监听器容器
     */
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);

        // 可以添加多个监听队列订阅频道
        // addMessageListener(MessageListener listener, Topic topic)
        // removeMessageListener(MessageListener listener, Collection<? extends Topic> topics)
        redisMessageListenerContainer.addMessageListener(new MessageListenerAdapter(myListener), new PatternTopic(
                "MYTOPIC"));
        return redisMessageListenerContainer;
    }
}
